package com.wlyuan.index.remote.consumer;

import com.wlyuan.index.remote.store.MessageStore;
import com.wlyuan.rabbit.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.function.Consumer;

@Slf4j
public abstract class AbstractMessageConsumer<T> {
    protected static class Exchanges {
        protected static final String ORDER = "exchange.topic.order";
        protected static final String TRANSPORT = "exchange.topic.waybill";
        protected static final String QUOTATION = "exchange.topic.quotation";
        protected static final String FINANCE = "exchange.topic.finance";
    }

    protected static class Queues {
        protected static final String ORDER = "queue.topic.index.order";
        protected static final String WAYBILL = "queue.topic.index.waybill";
        protected static final String WAYBILL_REINDEX = "queue.topic.index.waybill.reindex";
        protected static final String COMBINE = "queue.topic.index.combine";
        protected static final String COMBINE_REINDEX = "queue.topic.index.combine.reindex";
        protected static final String QUOTATION = "queue.topic.index.quotation";
        protected static final String BILL = "queue.topic.index.bill";
        protected static final String BILL_REINDEX = "queue.topic.index.bill.reindex";
        protected static final String BALANCE = "queue.topic.index.balance";
    }

    @Autowired
    private MessageStore messageStore;


    private T parseMessage(String string, Class<T> messageClass) {
        if (StringUtils.isEmpty(string)) {
            logger.error("消息内容为空: {}", messageClass);
            return null;
        }

        // 临时保存
        messageStore.add(messageClass, string);

        // 消息解析
        var message = MessageUtils.parse(string, messageClass);
        if (null == message) {
            logger.error("消息解析失败: {} {}", string, messageClass);
            return null;
        }
        return message;
    }

    protected void handle(String string, Class<T> messageClass, Consumer<T> consumer) {
        var message = this.parseMessage(string, messageClass);
        if (null != message) {
            consumer.accept(message);
        }
    }
}
